import os
import sys
from loguru import logger
from typing import List, Set
import asyncio
import json
from datetime import datetime
import time

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.append(project_root)

from exchange_manager import ExchangeManager
from database_manager import DatabaseManager
from logs import setup_common_symbols_logger

class CommonSymbolsManager:
    def __init__(self, exchange_manager=None):
        self.exchange_manager = exchange_manager or ExchangeManager()
        self.logger = setup_common_symbols_logger()
        
        # 先初始化数据库
        self.db_manager = DatabaseManager()
        
        # 然后获取共同交易对
        self.common_symbols = self.get_common_symbols()

    def get_common_symbols(self) -> List[str]:
        """获取所有共同交易对"""
        try:
            # 从数据库获取交易对
            symbols = self.db_manager.get_common_symbols()

            # 验证这些交易对在所有交易所中是否可用
            exchanges = self.exchange_manager.get_all_exchanges()
            valid_symbols = []
            
            for symbol in symbols:
                is_valid = True
                for exchange_id in exchanges:
                    exchange = exchanges[exchange_id]
                    try:
                        # 直接使用已经加载好的markets数据，不再重复调用API
                        markets = exchange.markets
                        if markets is None or symbol not in markets:
                            is_valid = False
                            break
                    except Exception:
                        is_valid = False
                        break
                
                if is_valid:
                    valid_symbols.append(symbol)
            
            self.logger.info(f"从数据库获取到 {len(valid_symbols)} 个有效的共同交易对")
            return valid_symbols
            
        except Exception as e:
            self.logger.error(f"获取共同交易对失败: {str(e)}")
            return []

    def should_update_symbols(self) -> bool:
        """检查是否需要更新共同交易对（每7天更新一次）"""
        try:
            # 从数据库获取上次更新时间
            last_update_time = self.db_manager.get_last_update_time()
            if last_update_time is None:
                return True
                
            current_time = time.time()
            # 检查是否已经过了7天
            if current_time - last_update_time < 7 * 24 * 60 * 60:
                self.logger.info(f"上次更新时间为 {datetime.fromtimestamp(last_update_time).strftime('%Y-%m-%d %H:%M:%S')}，未到7天，跳过更新")
                return False
            return True
        except Exception as e:
            self.logger.error(f"检查更新时间出错: {str(e)}")
            return True

    async def update_common_symbols(self):
        """更新共同交易对列表"""
        # 检查是否需要更新
        if not self.should_update_symbols():
            self.logger.info("使用现有的共同交易对数据")
            return self.get_common_symbols()
            
        self.logger.info("开始更新共同交易对...")
        
        try:
            # 获取所有交易所的交易对
            all_symbols = {}
            exchanges = self.exchange_manager.get_all_exchanges()
            
            if not exchanges:
                self.logger.error("没有可用的交易所")
                return []
            
            # 确保市场数据已加载
            for exchange_id, exchange in exchanges.items():
                if not hasattr(exchange, 'markets') or exchange.markets is None:
                    self.logger.info(f"{exchange_id} 市场数据未加载，正在加载...")
                    await self.exchange_manager.loadMarkets(exchange_id)
            
            # 创建保存市场数据的目录
            # save_dir = 'exchange_symbols'
            # if not os.path.exists(save_dir):
            #     os.makedirs(save_dir)
                    
            for exchange_id, exchange in exchanges.items():
                try:
                    # 使用已加载的市场数据
                    markets = exchange.markets
                    symbols = set()
                    
                    # 保存市场数据到文件
                    # save_file = os.path.join(save_dir, f"{exchange_id}_swap_markets.json")
                    
                    for market_id, market in markets.items():
                        try:
                            # 更严格的交易对过滤条件
                            if (market.get('type') == 'swap' and  # 必须是永续合约
                                market.get('quote') == 'USDT' and  # 计价货币必须是USDT
                                market.get('active') is True and   # 交易对必须处于活跃状态
                                market_id.endswith(':USDT')):      # 交易对ID必须以:USDT结尾
                                
                                symbols.add(market_id)
                                    
                        except Exception as e:
                            self.logger.debug(f"处理交易对 {market_id} 时出错: {str(e)}")
                            continue
                    
                    # 保存市场数据到文件
                    # with open(save_file, 'w', encoding='utf-8') as f:
                    #     json.dump(list(symbols), f, indent=2, ensure_ascii=False)
                    
                    all_symbols[exchange_id] = symbols
                    self.logger.info(f"{exchange_id} 获取到 {len(symbols)} 个符合条件的交易对")
                    
                except Exception as e:
                    self.logger.error(f"{exchange_id} 获取交易对失败: {str(e)}")
                    all_symbols[exchange_id] = set()

            # 找出共同交易对
            if not all_symbols:
                self.logger.error("没有获取到任何交易对")
                return []
                
            common_symbols = set.intersection(*all_symbols.values())
            
            # 记录每个交易所特有的交易对
            for exchange_id, symbols in all_symbols.items():
                unique_symbols = symbols - common_symbols
                if unique_symbols:
                    self.logger.debug(f"{exchange_id} 特有的交易对: {len(unique_symbols)}")
            
            self.logger.info(f"找到 {len(common_symbols)} 个共同交易对")

            # 保存到数据库
            if common_symbols:
                try:
                    # 尝试保存共同交易对
                    self.db_manager.save_common_symbols(list(common_symbols))
                    self.logger.info(f"成功保存 {len(common_symbols)} 个共同交易对到数据库")
                    
                except Exception as e:
                    self.logger.error(f"保存共同交易对到数据库失败: {str(e)}")
                    
                    # 如果保存失败，尝试修复表结构而不是删除整个数据库
                    try:
                        self.logger.info("尝试修复数据库表结构...")
                        # 重新初始化数据库管理器，这会检查并修复表结构
                        self.db_manager = DatabaseManager()
                        
                        # 再次尝试保存
                        self.db_manager.save_common_symbols(list(common_symbols))
                        self.logger.info("修复表结构后保存成功")
                        
                    except Exception as e2:
                        self.logger.error(f"修复表结构后仍然失败: {str(e2)}")
            
            return list(common_symbols)
            
        except Exception as e:
            self.logger.error(f"更新共同交易对失败: {str(e)}")
            return []

async def main():
    """测试共同交易对管理"""
    manager = CommonSymbolsManager()
    
    # 更新共同交易对
    logger.info("开始更新共同交易对...")
    common_symbols = await manager.update_common_symbols()
    
    # 显示结果
    if common_symbols:
        logger.info("共同交易对列表:")
        for symbol in sorted(common_symbols):
            logger.info(f"  {symbol}")
    else:
        logger.error("未找到共同交易对")

if __name__ == "__main__":
    asyncio.run(main()) 